package com.ant.xmla.datacrawling.utils.fileUtli;


import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * 文件输入输出流操作
 * @Author 中国蚂蚁技术有限公司
 * @create 2020/9/17 18:50
 */
public class FileReadWriteUtil {

    private static Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]");

    /**
     * @Description:打印日志
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/17 18:57
     * @Param:  [context]
     * @return: void
     * */
    public static void printLog(String context) {
        String path = String.format("E://喜马拉雅//有声书下载日志//%s.txt", DateUtil.format(new Date(),"yyyy-MM-dd"));
        BufferedWriter fw = null;
        try {
            File file = new File(path);
            file.getParentFile().mkdirs();
            if (file.exists())
                file.createNewFile();
            fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); // 指定编码格式，以免读取时中文字符异常
            fw.write("");
            fw.newLine();
            fw.append(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:sss").format(new Date()) + "-->" + context);
            fw.flush(); // 全部写入缓存中的内容
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @Description:音频下载
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/17 18:57
     * @Param:  [remoteSourceUrl, tmpFileFolder]
     * @return: java.lang.String
     * */
    public static void downloadSource(String remoteSourceUrl, String tmpFileFolder) throws Exception {
        //下载资源
        URL url = new URL(remoteSourceUrl);
        DataInputStream dataInputStream = new DataInputStream(url.openStream());
        //进行判断url
        if (remoteSourceUrl.contains("?")){
            remoteSourceUrl = remoteSourceUrl.substring(0,remoteSourceUrl.indexOf("?"));
            System.out.println("vip分割后的路径:"+remoteSourceUrl);
        }
        String fileName = getOriginalFileName(remoteSourceUrl);
        String newUrl = fileName.substring(fileName.indexOf("."));
        String tmpFilePath = tmpFileFolder + newUrl;
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFilePath);
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = dataInputStream.read(bytes)) != -1) {
            fileOutputStream.write(bytes, 0, length);
        }
        dataInputStream.close();
        fileOutputStream.close();
    }
    /**
     * 根据文件url获取文件名（包含后缀名）
     *
     * @param url 文件url
     * @return 文件名（包含后缀名）
     */
    private static String getOriginalFileName(String url) {
        String[] sarry = url.split("/");
        return sarry[sarry.length - 1];
    }
    /**
     * @Description:文件重命名,大量的进行读写改名操作效率极慢
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/18 11:33
     * @Param:  [oldFileName, newFileName]
     * @return: java.lang.String
     * */
    public static String rechristen(String oldFileName,String newFileName){
        StringBuilder voiceUrl = new StringBuilder();
        String downVoice = PropertiesUtil.getDocking("DOWN_VOICE");
        String downSuffix = PropertiesUtil.getDocking("DOWN_SUFFIX");
        voiceUrl.append(downVoice);
        voiceUrl.append(newFileName);
        voiceUrl.append(downSuffix);
        File oldName = new File(oldFileName);
        System.out.println(voiceUrl.toString());
        File newName = new File(voiceUrl.toString());
        if(oldName.renameTo(newName)) {
           return "重命名成功";
        }else {
            return "重命名失敗";
        }
    }
    /**
     * @Description:创建文件夹
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/21 17:01
     * @Param:  []
     * @return: void
     * */
    public static String createFile(String name){
        String filterName = filterChar(name);
        String path = String.format("E://喜马拉雅//有声书下载//%s",filterName);
        try {
            File file = new File(path);
            file.getParentFile().mkdirs();
            if (file.exists())
                file.createNewFile();
            return file.getPath();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * @Description:特殊字符过滤
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/21 17:23
     * @Param:  [audioName]
     * @return: java.lang.String
     * */
    private static String filterChar(String audioName){
        String replaceName = FilePattern.matcher(audioName).replaceAll("");
        return StringUtils.isBlank(audioName) ?"无文件名请自定义修改":replaceName;
    }
}
